package com.an.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.an.blog.admin.domain.BlogFriendLink;
import com.an.blog.admin.domain.bo.BlogFriendLinkBo;
import com.an.blog.admin.domain.vo.BlogFriendLinkVo;
import com.an.blog.mapper.BlogFriendLinkMapper;
import com.an.blog.service.IBlogFriendLinkService;
import com.an.blog.utils.ConvertUtil;
import com.an.blog.web.domain.bo.BlogFriendLinkWebBo;
import com.an.blog.web.domain.vo.BlogFriendLinkWebVo;
import com.an.common.constant.BlogConstants;
import com.an.common.constant.MqConstants;
import com.an.common.core.domain.BaseEntity;
import com.an.common.core.domain.PageQuery;
import com.an.common.core.domain.bo.SendCodeBo;
import com.an.common.core.domain.entity.SysUser;
import com.an.common.core.page.TableDataInfo;
import com.an.common.enums.CodeTemplateType;
import com.an.common.exception.blog.BlogException;
import com.an.common.utils.StringUtils;
import com.an.producer.MqProducer;
import com.an.system.domain.vo.SysOssVo;
import com.an.system.mapper.SysUserMapper;
import com.an.system.service.ISysOssService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 博客友链Service业务层处理
 *
 * @author Ann
 * @date 2023-10-17
 */
@RequiredArgsConstructor
@Service
public class BlogFriendLinkServiceImpl implements IBlogFriendLinkService {

    private final BlogFriendLinkMapper baseMapper;
    private final SysUserMapper sysUserMapper;
    private final ISysOssService ossService;
    private final MqProducer mqProducer;

    /**
     * 查询博客友链
     */
    @Override
    public BlogFriendLinkVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询博客友链列表
     *
     * @param bo        薄
     * @param pageQuery 页面查询
     * @return {@link TableDataInfo }<{@link BlogFriendLinkVo }>
     * @author: Ann
     * @createDate: 2023/10/17 14:17:21
     * @version: 1.0.0
     */
    @Override
    public TableDataInfo<BlogFriendLinkVo> queryPageList(BlogFriendLinkBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BlogFriendLink> lqw = buildQueryWrapper(bo);
        Page<BlogFriendLinkVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (result.getTotal() < 1) {
            return TableDataInfo.build(result);
        }
        List<BlogFriendLinkVo> records = result.getRecords();
        Map<Long, SysOssVo> sysOssVoMap = ConvertUtil.convert2OssIdSysOssMap(records, BlogFriendLinkVo::getBlogLogoImage);
        records.forEach(blogFriendLinkVo -> {
            SysOssVo sysOssVo = sysOssVoMap.get(blogFriendLinkVo.getBlogLogoImage());
            blogFriendLinkVo.setBlogLogoImageUrl(sysOssVo != null ? sysOssVo.getUrl() : null);
        });
        return TableDataInfo.build(records, result.getTotal());
    }

    /**
     * 查询博客友链列表
     *
     * @param bo 薄
     * @return {@link List }<{@link BlogFriendLinkVo }>
     * @author: Ann
     * @createDate: 2023/10/19 15:40:23
     * @version: 1.0.0
     */
    @Override
    public List<BlogFriendLinkVo> queryList(BlogFriendLinkBo bo) {
        LambdaQueryWrapper<BlogFriendLink> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BlogFriendLink> buildQueryWrapper(BlogFriendLinkBo bo) {
        LambdaQueryWrapper<BlogFriendLink> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getBlogTitle()), BlogFriendLink::getBlogTitle, bo.getBlogTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), BlogFriendLink::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增博客友链
     *
     * @param bo 薄
     * @return {@link Boolean }
     * @author: Ann
     * @createDate: 2023/10/19 15:40:39
     * @version: 1.0.0
     */
    @Override
    public Boolean insertByBo(BlogFriendLinkBo bo) {
        BlogFriendLink add = BeanUtil.toBean(bo, BlogFriendLink.class);
        add.setStatus(BlogConstants.FRIEND_LINK_CHECKED);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改博客友链
     *
     * @param bo 薄
     * @return {@link Boolean }
     * @author: Ann
     * @createDate: 2023/10/19 15:40:41
     * @version: 1.0.0
     */
    @Override
    public Boolean updateByBo(BlogFriendLinkBo bo) {
        BlogFriendLink update = BeanUtil.toBean(bo, BlogFriendLink.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BlogFriendLink entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除博客友链
     *
     * @param ids     id
     * @param isValid 是有效
     * @return {@link Boolean }
     * @author: Ann
     * @createDate: 2023/10/19 15:40:48
     * @version: 1.0.0
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 按id检查
     *
     * @param ids id
     * @return {@link Boolean }
     * @author: Ann
     * @createDate: 2023/10/17 14:56:26
     * @version: 1.0.0
     */
    @Override
    public Boolean checkByIds(Collection<Long> ids) {
        //检查数据中是否包含已经审核过的了
        checkIsChecked(ids);
        //检查是否包含已审核的数据
        List<BlogFriendLink> blogFriendLinks = ids.stream().map(id -> {
            BlogFriendLink blogFriendLink = new BlogFriendLink();
            blogFriendLink.setId(id);
            blogFriendLink.setStatus(BlogConstants.FRIEND_LINK_CHECKED);
            return blogFriendLink;
        }).collect(Collectors.toList());
        return baseMapper.updateBatchById(blogFriendLinks);
    }

    /**
     * 取消检查
     *
     * @param id id
     * @return {@link Boolean }
     * @author: Ann
     * @createDate: 2023/10/17 15:07:02
     * @version: 1.0.0
     */
    @Override
    public Boolean cancelCheck(Long id) {
        boolean exists = baseMapper.exists(new LambdaQueryWrapper<BlogFriendLink>().eq(BlogFriendLink::getId, id)
            .eq(BlogFriendLink::getStatus, BlogConstants.FRIEND_LINK_WAIT_CHECK));
        if (exists) {
            throw new BlogException("blog.friend.link.non.checked");
        }
        BlogFriendLink blogFriendLink = new BlogFriendLink();
        blogFriendLink.setId(id);
        blogFriendLink.setStatus(BlogConstants.FRIEND_LINK_WAIT_CHECK);
        //改为待审核状态
        return baseMapper.updateById(blogFriendLink) > 0;
    }

    /**
     * 查询好友链接web列表
     *
     * @return {@link List }<{@link BlogFriendLinkWebVo }>
     * @author: Ann
     * @createDate: 2023/10/23 15:58:48
     * @version: 1.0.0
     */
    @Override
    public List<BlogFriendLinkWebVo> queryFriendLinkWebList() {
        List<BlogFriendLinkVo> blogFriendLinkVos = baseMapper.selectVoList(new LambdaQueryWrapper<BlogFriendLink>()
            .select(BlogFriendLink::getId, BlogFriendLink::getBlogTitle,
                BlogFriendLink::getBlogDesc, BlogFriendLink::getBlogAddress,
                BlogFriendLink::getBlogLogoImage)
            .eq(BlogFriendLink::getStatus, BlogConstants.FRIEND_LINK_CHECKED)
            .orderByAsc(BaseEntity::getCreateTime));
        return BeanUtil.copyToList(blogFriendLinkVos, BlogFriendLinkWebVo.class);
    }

    /**
     * 申请好友链接
     *
     * @param blogFriendLinkWebBo 博客好友链接网站博
     * @return {@link Boolean }
     * @author: Ann
     * @createDate: 2023/10/24 16:31:15
     * @version: 1.0.0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean applyForFriendLink(BlogFriendLinkWebBo blogFriendLinkWebBo) {
        //图片链接地址
        String blogLogoImage = blogFriendLinkWebBo.getBlogLogoImage();
        String blogTitle = blogFriendLinkWebBo.getBlogTitle();
        //通过图片链接上传
        SysOssVo ossVo = ossService.uploadByUrl(blogTitle, blogLogoImage);
        BlogFriendLink blogFriendLink = new BlogFriendLink();
        blogFriendLink.setBlogTitle(blogTitle);
        blogFriendLink.setBlogAddress(blogFriendLinkWebBo.getBlogAddress());
        blogFriendLink.setBlogDesc(blogFriendLinkWebBo.getBlogDesc());
        blogFriendLink.setBlogLogoImage(ossVo.getOssId());
        blogFriendLink.setStatus(BlogConstants.FRIEND_LINK_WAIT_CHECK);
        boolean inserted = baseMapper.insert(blogFriendLink) > 0;
        if (inserted) {
            //管理员账号
            SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, "1"));
            SendCodeBo sendCodeBo = new SendCodeBo();
            sendCodeBo.setEmail(sysUser.getEmail());
            sendCodeBo.setType(CodeTemplateType.FRIEND_LINK_REMIND_TEMPLATE.getType());
            mqProducer.sendMessage(MqConstants.MAIL_EXCHANGE, MqConstants.MAIL_SEND_KEY, sendCodeBo);
        }
        return inserted;
    }

    /**
     * 检查被检查了
     *
     * @param ids id
     * @author: Ann
     * @createDate: 2023/10/17 14:59:41
     * @version: 1.0.0
     */
    private void checkIsChecked(Collection<Long> ids) {
        boolean exists = baseMapper.exists(new LambdaQueryWrapper<BlogFriendLink>()
            .eq(BlogFriendLink::getStatus, BlogConstants.FRIEND_LINK_CHECKED)
            .in(BlogFriendLink::getId, ids));
        if (exists) {
            throw new BlogException("blog.friend.link.has.checked");
        }
    }
}
